<?php

namespace app\controller\property\contract;

use think\App;
use app\controller\property\Base;
use think\exception\ValidateException;
use app\validate\contract\ContractBasicValidate;
use app\common\repositories\bill\BillCateRepository;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\contract\ContractLogRepository;
use app\common\repositories\contract\ContractBasicRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;


class ContractBasic extends Base
{
    protected $repository;

    public function __construct(App $app, ContractBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyContractBasicAdd'),
            'editAuth' => property_auth('propertyContractBasicEdit'),
            'delAuth' => property_auth('propertyContractBasicDel'),
            'detailAuth' => property_auth('propertyContractBasicDetail'),
        ]);
    }

    protected function commonParams()
    {
        /** @var BillCateRepository $cateRepository */
        $cateRepository = app()->make(BillCateRepository::class);
        $cateNameData = $cateRepository->getCascaderData($this->request->propertyId, ['is_show' => 1]);
        $this->assign([
            'cateNameData' => $cateNameData,
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'keywords' => '',
                'time' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        $this->commonParams();
        return $this->fetch('contract/basic/list');
    }

    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'roomData') {
            /** @var RoomBasicRepository $roomRepository */
            $roomRepository = app()->make(RoomBasicRepository::class);
            $roomData = $roomRepository->getSearch([])
                ->where('status', 1)
                ->where('property_id', $this->request->propertyId)
                ->append(['full_room_name'])
                ->select()->toArray();
            $roomData['number'] = $this->repository->generateContractNumber($this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $roomData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'room_id' => '',
                'rent_date' => '',
                'room_rent' => '',
                'room_deposit' => '',
                'pay_type' => '',
                'sign_type' => '',
                'number' => '',
                'start_date' => '',
                'end_date' => '',
                'bill_month' => '',
                'bill_pay_day' => '',
                'bill_add_day' => '',
                'bill_prompt' => '',
                'overdue_fine' => '',
                'remark' => '',
                'out_fee_flag' => '',
                'is_rose' => '',
                'next_years' => '',
                'next_rose_rate' => '',
                'next_rose_date' => '',
                'next_rose_rent' => '',
                'picture' => [],
                'other_fee' => [],
                'lessee_info' => [],
                'end_method' => '',
                'sign_audit' => '',
                'template_id' => '',
            ]);
            validate(ContractBasicValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('number', $param['number'])) {
                return $this->error('租赁编号' . $param['number'] . '已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加合同失败', $e);
                return $this->error('网络失败');
            }
        } else {
            /** @var BillCateRepository $cateRepository */
            $cateRepository = app()->make(BillCateRepository::class);
            $cateNameData = $cateRepository->getCascaderData($this->request->propertyId, ['is_show' => 1, 'is_class' => 3]);
            return $this->fetch('contract/basic/add', [
                'cateNameData' => $cateNameData,
            ]);
        }
    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        if (!$this->repository->exists($id)) {
            return $this->error('租赁不存在');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'out_fee_flag' => '',
                'is_rose' => '',
                'next_years' => '',
                'next_rose_rate' => '',
                'next_rose_date' => '',
                'next_rose_rent' => '',
                'bill_add_day' => '',
                'bill_month' => '',
                'bill_pay_day' => '',
                'overdue_fine' => '',
                'sign_type' => '',
                'sign_audit' => '',
                'end_method' => '',
                'picture' => [],
                'remark' => '',
                'template_id' => '',
            ]);
            validate(ContractBasicValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改合同失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('contract/basic/edit', [
                'info' => $info,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除合同失败', $e);
            return $this->error($e->getMessage());
        }
    }


    public function detail()
    {
        $contractId = (int)$this->request->param('contract_id');
        if ($contractId <= 0) {
            return $this->error('参数错误');
        }
        $contractInfo = $this->repository->getDetail($contractId);
        if ($contractInfo['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('contract/basic/detail', [
            'contractInfo' => $contractInfo,
            'auditAuth' => property_auth('propertyContractBasicAudit'),#审核
            'extendAuth' => property_auth('propertyContractBasicExtend'),#续租
            'renunAuth' => property_auth('propertyContractBasicRenun'),#退租
            'detailBillAuth' => property_auth('propertyBillBasicDetail'),#账单详情
            'boundRoomBillAuth' => property_auth('propertyContractRoomBound'),#账单详情
        ]);
    }

    /**
     * 审核确认
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-20 14:44
     */
    public function auditContract()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        if (!$this->repository->propertyExists($this->request->propertyId, $id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if ($info['status'] != 1) {
            return $this->error('此租赁状态不可审核');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'status' => 1,
                'remark' => '',
            ]);
            validate(ContractBasicValidate::class)->scene('audit')->check($param);
            try {
                $data = $this->repository->auditSuccess($info['id'], $param['status'], $this->request->userId, '手动审核');
                if ($data) {
                    return $this->success('审核成功');
                } else {
                    return $this->error('审核失败');
                }
            } catch (\Exception $e) {
                exception_log('审核同失败', $e);
                return $this->error('网络失败' . $e->getMessage());
            }
        } else {
            return $this->fetch('contract/basic/approval', [
                'info' => $info,
            ]);
        }
    }


    /**
     * 续租
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-20 14:31
     */
    public function extendContract()
    {
        $contractId = (int)$this->request->param('contract_id');
        if (!$contractId) {
            return $this->error('参数错误');
        }
        if (!$this->repository->propertyExists($this->request->propertyId, $contractId)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($contractId);
        if ($info['status'] != 2) {
            return $this->error('此租赁不可进行此操作');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'end_date' => '',
            ]);
            if ($info['status'] != 2) {
                return $this->error('此租赁不可续期');
            }
            if ($param['end_date'] <= $info['end_date']) {
                return $this->error('续租日期必须大于结束日期');
            }
            try {
                $res = $this->repository->extendContract($info['id'], $param['end_date'], $this->request->userId);
                if ($res) {
                    return $this->success('成功续租至' . $param['end_date']);
                } else {
                    return $this->error('续租失败');
                }
            } catch (\Exception $e) {
                exception_log('租赁续租失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('contract/basic/extend', [
                'info' => $info,
            ]);
        }
    }


    /**
     * 租赁退租
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-20 14:53
     */
    public function renunContract()
    {
        $contractId = (int)$this->request->param('contract_id');
        if (!$contractId) {
            return $this->error('参数错误');
        }
        if (!$this->repository->propertyExists($this->request->propertyId, $contractId)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($contractId);
        if ($info['status'] != 2) {
            return $this->error('此租赁不可进行此操作');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'refund_type' => '',
                'remark' => '',
            ]);
            validate(ContractBasicValidate::class)->scene('renun')->check($param);
            try {
                $res = $this->repository->refundContract($info['id'], $param, $this->request->userId);
                if ($res) {
                    return $this->success('退租成功');
                } else {
                    return $this->error('退租失败');
                }
            } catch (\Exception $e) {
                exception_log('租赁信息退租失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var BillCateRepository $cateRepository */
            $cateRepository = app()->make(BillCateRepository::class);

            /** @var BillBasicRepository $billBasicRepository */
            $billBasicRepository = app()->make(BillBasicRepository::class);
            $info['bill_number'] = $billBasicRepository->generateBillNumber($info['property_id']);
            $cateNameData = $cateRepository->getCascaderData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('contract/basic/refund', [
                'info' => $info,
                'cateNameData' => $cateNameData,
            ]);
        }
    }


    /**
     *  绑定房间信息
     * @param RoomBasicRepository $roomRepository
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-20 10:21
     */
    public function roomBound(RoomBasicRepository $roomRepository)
    {
        $contractId = (int)$this->request->param('contract_id');
        $info = $this->repository->get($contractId);
        if ($this->request->isAjax() && $this->request->isGet()) {
            $where = $this->request->param([
                'keyword' => '',
                'status' => 1,
            ]);
            [$page, $limit] = $this->getPage();
            $res = $roomRepository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        } else {
            if (!$contractId) {
                return $this->error('参数错误');
            }
            if (!$this->repository->propertyExists($this->request->propertyId, $contractId)) {
                return $this->error('数据不存在');
            }
            if ($this->request->isPost()) {
                $ids = (array)$this->request->param('room_id');
                $data = $this->repository->batchRoomBound($info, $ids, $this->request->userId);
                if ($data) {
                    return $this->success('绑定成功');
                } else {
                    return $this->error('绑定失败');
                }
            } else {
                return $this->fetch('contract/room/bound_room', [
                    'info' => $info
                ]);
            }
        }
    }


    /**
     * 解除关联房间
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-03-20 12:09
     */
    public function roomRelieve()
    {
        $roomId = (int)$this->request->param('id');
        /** @var RoomBasicRepository $roomRepository */
        $roomRepository = app()->make(RoomBasicRepository::class);
        $roomInfo = $roomRepository->get($roomId);
        $contractInfo = $this->repository->get($roomInfo['contract_id']);
        if ($roomId == $contractInfo['room_id']) {
            return $this->error('合同主房间禁止解除');
        }
        try {
            $data = $roomRepository->roomRelieve($roomId, $contractInfo['id'], $this->request->userId);
            if ($data) {
                return $this->success('解绑成功');
            } else {
                return $this->error('解绑失败');
            }
        } catch (\Exception $e) {
            return $this->error('网络失败');
        }
    }

    public function contractLog(ContractLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getList($where, $page, $limit);

            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }
}